package network_programming.np1_socket_and_serversocket;


import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 发送邮件的SMTP客户程序
 * */
public class MailSender {
    private String smtpServer = "smtp.abc.com";     // SMTP服务器主机名
    private int port = 25;
    public void sendMail(Message msg) {
        try (Socket socket = new Socket(smtpServer, port)) {
            BufferedReader br = getReader(socket);
            PrintWriter pw = getWriter(socket);
            String localhost = InetAddress.getLocalHost().getHostName();    // 本地主机名
            sendAndReceive(null, br, pw);       // 仅仅为了接收服务器的响应数据
            sendAndReceive("HELO " + localhost, br, pw);    // HELO     指明发送邮件发送者的主机地址
            sendAndReceive("MAIL FROM: <" + msg.from + ">", br, pw);    // 指明邮件发送者的邮件地址
            sendAndReceive("RCPT TO: <" + msg.to, br, pw);  // 指明邮件接收者的邮件地址
            sendAndReceive("DATA", br, pw);     // 表示接下来讲发送邮件内容
            pw.println(msg.data);       // 发送邮件内容
            System.out.println("Client>" + msg.data);
            sendAndReceive(".", br, pw);        // “.”  表示邮件内容发送完毕
            sendAndReceive("QUIT", br, pw);     // 结束通信
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIS = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIS));
    }
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOS = socket.getOutputStream();
        return new PrintWriter(socketOS, true);
    }
    /* 发送一行字符串，并接收一行服务器的响应数据 */
    private void sendAndReceive(String str, BufferedReader br, PrintWriter pw) throws IOException {
        if(str != null) {
            System.out.println("Client>" + str);
            pw.println(str);    // 发送字符串后，还会发送“\r\n”
        }
        String response;
        if((response = br.readLine()) != null)
            System.out.println("Server>" + response);
    }

    public static void main(String[] args) {
        Message msg = new Message("tom@abc.com", "linda@def.com", "hello",
                "hi, I miss you very much.");
        new MailSender().sendMail(msg);
    }
}

class Message {     // 邮件类
    String from;    // 发送者的邮件地址
    String to;      // 接收者的邮件地址
    String subject; // 邮件标题
    String content; // 邮件正文
    String data;    // 邮件内容，包括邮件标题和正文
    public Message(String from, String to, String subject, String content) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.data = "Subject:" + subject + "\r\n" + content;
    }
}